package com.fingard.dsp.bank.directbank.zjrc01;


import com.fingard.dsp.bank.directbank.PaymentState;
import com.fingard.dsp.bank.directbank.bankInterface.ISinglePay;
import com.fingard.dsp.bank.reqrespobj.single.*;
import com.fingard.dsp.bank.reqrespobj.single.detail.RetAtsSglDetail;
import com.fingard.net.ConnState;
import com.fingard.text.StringHelper;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

public class ZJRC01SinglePay extends ZJRC01Base implements ISinglePay {

    //单笔支付，不需采用流处理方式
    public RetAtsSingle d_1908_SglPay(ReqSingle p_req1908) throws Exception {
        //返回ATS的对象
        RetAtsSingle retAts = new RetAtsSingle(p_req1908.reqHeader);
        RetAtsSglDetail tmpRetDetail;
        tmpRetDetail = externalPayments(p_req1908);
        if (tmpRetDetail.respCode.equals("-1") && StringHelper.isNullOrEmpty(tmpRetDetail.reqSeqID)) {
            tmpRetDetail.reqSeqID = p_req1908.singleDetail.askNumber;
        }
        retAts.writeRetDetail(tmpRetDetail);
        return retAts;
    }

    @Override
    public RetAtsSingleBat d_1908BAT_SglBatPay(ReqSingleBat p_req1908BAT) throws Exception {
        return null;
    }

    //190802对外支付
    private RetAtsSglDetail externalPayments(ReqSingle p_req1908) throws Exception {
        RetAtsSglDetail retDetail = new RetAtsSglDetail();
        if (p_req1908.singleDetail.sameBnk.equals("1")) {//同行
            bankInnerTransfer(p_req1908, retDetail);
        } else {//跨行
            crossBankTransfer(p_req1908, retDetail);
        }
        return retDetail;
    }

    //同行支付
    private RetAtsSglDetail bankInnerTransfer(ReqSingle p_req1908, RetAtsSglDetail retDetail) throws Exception {
        String payeeType = "";
        String isSameCity = "";
        tranCode = "100004";
        serialNo = p_req1908.reqHeader.reqSeqID;
        XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
        //写入报文头部信息
        writeCommonHeader(xmlWriter);
        xmlWriter.writeElementString("payAccount", p_req1908.singleDetail.payAct);
        xmlWriter.writeElementString("payAccountName", p_req1908.singleDetail.payName);
        xmlWriter.writeElementString("currencyType", convertCurToBank(p_req1908.singleDetail.payCur));
        xmlWriter.writeElementString("payAmount", p_req1908.singleDetail.payAmount);
        xmlWriter.writeElementString("payUse", p_req1908.singleDetail.purpose);
        xmlWriter.writeElementString("payRem", p_req1908.singleDetail.memo);
        xmlWriter.writeElementString("recAccount", p_req1908.singleDetail.recAct);
        xmlWriter.writeElementString("recAccountName", p_req1908.singleDetail.recName);
        if ("1".equals(p_req1908.singleDetail.sameCity)) {
            isSameCity = "0";
        } else {
            isSameCity = "1";
        }
        if ("1".equals(p_req1908.singleDetail.isPrivate)) {
            payeeType = "0";
        } else {
            payeeType = "1";
        }
        xmlWriter.writeElementString("transferTowardType", isSameCity);
        xmlWriter.writeElementString("tranMate", payeeType);
        xmlWriter.writeEndElement();
        xmlWriter.writeEndDocument();//报文结束
        String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());//发送给银行
        //模拟银行返回
        /*tmpStrRet[0] = "";
        tmpStrRet[1] ="<?xml version=\"1.0\" encoding=\"GBK\"?>\n" +
                "<ebank>\n" +
                "\t<resHead>\n" +
                "\t\t<retCode>0000</retCode>\n" +
                "\t\t<errMsg>消息</errMsg>\n" +
                "\t\t<serialNo>12345678</serialNo>\n" +
                "\t</resHead>\n" +
                "\t<resBody>\n" +
                "\t\t\t\t<DFJGDH>123</DFJGDH>\n" +
                "\t\t\t\t<commFlowNo>9876543</commFlowNo>\n" +
                "\t</resBody>\n" +
                "</ebank>\n";*/
        if (tmpStrRet[0].length() == 0) {
            StringBuilder tmpSbMsg = new StringBuilder();
            //解析银行返回
            int index = tmpStrRet[1].indexOf("</ebank>");
            tmpStrRet[1] = tmpStrRet[1].substring(0,index+8);
            XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
            if (tmpBkReader != null) {
                retDetail.respCode = "0";
                retDetail.respInfo = tmpBkReader.getFirstText("/ebank/resHead/errMsg");
                retDetail.reqSeqID = p_req1908.singleDetail.askNumber;
                retDetail.transState = tmpBkReader.getFirstText("/ebank/resHead/retCode");
                retDetail.payInfoCode = retDetail.transState;
            } else {
                retDetail.respCode = "-1";
                retDetail.respInfo = tmpSbMsg.toString();
            }
        } else if (tmpStrRet[0].equals(ConnState.FAIL)) {
            retDetail.respCode = "0";
            retDetail.respInfo = tmpStrRet[1];
            retDetail.reqSeqID = p_req1908.singleDetail.askNumber;
            retDetail.transState = PaymentState.FAIL_Payment;
            retDetail.payInfoCode = tmpStrRet[0];
        } else {
            retDetail.respCode = "-1";
            retDetail.respInfo = tmpStrRet[1];
        }
        return retDetail;
    }

    //跨行支付
    private RetAtsSglDetail crossBankTransfer(ReqSingle p_req1908, RetAtsSglDetail retDetail) throws Exception {
        String isSameCity = "";
        String payeeType = "";
        tranCode = "100005";
        serialNo = p_req1908.reqHeader.reqSeqID;
        XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
        writeCommonHeader(xmlWriter);
        xmlWriter.writeElementString("payAccount", p_req1908.singleDetail.payAct);
        xmlWriter.writeElementString("payAccountName", p_req1908.singleDetail.payName);
        xmlWriter.writeElementString("currencyType", convertCurToBank(p_req1908.singleDetail.payCur));
        xmlWriter.writeElementString("payAmount", p_req1908.singleDetail.payAmount);
        xmlWriter.writeElementString("payUse", p_req1908.singleDetail.purpose);
        xmlWriter.writeElementString("payRem", p_req1908.singleDetail.memo);
        xmlWriter.writeElementString("recAccount", p_req1908.singleDetail.recAct);
        xmlWriter.writeElementString("recAccountName", p_req1908.singleDetail.recName);
        xmlWriter.writeElementString("recAccountOpenBank", p_req1908.singleDetail.recBankLocation);
        xmlWriter.writeElementString("unionBankNo", p_req1908.singleDetail.cnapsCode);
        if ("1".equals(p_req1908.singleDetail.sameCity)) {
            isSameCity = "0";
        } else {
            isSameCity = "1";
        }
        xmlWriter.writeElementString("transferTowardType", isSameCity);
        String trsMode = "";
        if (p_req1908.singleDetail.isLargeAmt()) {
            trsMode = "1";
        } else if (p_req1908.singleDetail.paySpd.equals("1")) {//加急走大额
            trsMode = "1";
        } else {
            trsMode = "0";
        }
        xmlWriter.writeElementString("ZHYODJ", trsMode);
        //集中收费标志 1-逐笔 2-按月 3-按季 4-按年 （1逐笔表示非集中收费，其他为集中收费）
        xmlWriter.writeElementString("feePayType", "1");
        if ("1".equals(p_req1908.singleDetail.isPrivate)) {
            payeeType = "0";
        } else {
            payeeType = "1";
        }
        xmlWriter.writeElementString("tranMate", payeeType);
        xmlWriter.writeEndElement();
        xmlWriter.writeEndDocument();//写入报文完成
        String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());//发送银行
        //模拟银行返回
        /*tmpStrRet[0] = "";
        tmpStrRet[1] ="<?xml version=\"1.0\" encoding=\"GBK\"?>\n" +
                "<ebank>\n" +
                "\t<resHead>\n" +
                "\t\t<retCode>0000</retCode>\n" +
                "\t\t<errMsg>消息</errMsg>\n" +
                "\t\t<serialNo>12345678</serialNo>\n" +
                "\t</resHead>\n" +
                "\t<resBody>\n" +
                "\t\t\t\t<chargeFee>1.11</chargeFee>\n" +
                "\t\t\t\t<commFlowNo>9876543</commFlowNo>\n" +
                "\t</resBody>\n" +
                "</ebank>\n";*/
        if (tmpStrRet[0].length() == 0) {
            StringBuilder tmpSbMsg = new StringBuilder();
            int index = tmpStrRet[1].indexOf("</ebank>");
            tmpStrRet[1] = tmpStrRet[1].substring(0,index+8);
            XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
            if (tmpBkReader != null) {
                retDetail.respCode = "0";
                retDetail.respInfo = tmpBkReader.getFirstText("/ebank/resHead/errMsg");
                retDetail.reqSeqID = p_req1908.singleDetail.askNumber;
                retDetail.transState = tmpBkReader.getFirstText("/ebank/resHead/retCode");
                retDetail.payInfoCode = retDetail.transState;
            } else {
                retDetail.respCode = "-1";
                retDetail.respInfo = tmpSbMsg.toString();
            }
        } else if (tmpStrRet[0].equals(ConnState.FAIL)) {
            retDetail.respCode = "0";
            retDetail.respInfo = tmpStrRet[1];
            retDetail.reqSeqID = p_req1908.singleDetail.askNumber;
            retDetail.transState = PaymentState.FAIL_Payment;
            retDetail.payInfoCode = tmpStrRet[0];
        } else {
            retDetail.respCode = "-1";
            retDetail.respInfo = tmpStrRet[1];
        }
        return retDetail;
    }

    //1944 状态查询
    public RetAtsSingle d_1944_QrySglPay(ReqQrySingle p_req1944) throws Exception {
        //返回ATS的对象
        RetAtsSingle retAts = new RetAtsSingle(p_req1944.reqHeader);

        RetAtsSglDetail retDetail = new RetAtsSglDetail();
        tranCode = "100009";
        serialNo = p_req1944.reqHeader.reqSeqID;
        XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
        writeCommonHeader(xmlWriter);
        xmlWriter.writeElementString("flowNoType", "1");//0:网银流水(默认)1:企业指令序号
        xmlWriter.writeStartElement("flowNoList");
        xmlWriter.writeStartElement("row");
        xmlWriter.writeElementString("orderFlowNo", reqHeader.reqSeqID);
        xmlWriter.writeEndDocument();
        try {
            String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());
            //模拟银行返回
            /*tmpStrRet[0] = "";
            tmpStrRet[1] ="<?xml version=\"1.0\" encoding=\"GBK\"?>\n" +
                    "<ebank>\n" +
                    "\t<resHead>\n" +
                    "\t\t<retCode>0000</retCode>\n" +
                    "\t\t<errMsg>消息</errMsg>\n" +
                    "\t\t<serialNo>12345678</serialNo>\n" +
                    "\t</resHead>\n" +
                    "\t<resBody>\n" +
                    "\t\t<tranflowResultList>\n" +
                    "\t\t\t<row>\n" +
                    "\t\t\t\t<orderFlowNo>123456</orderFlowNo>\n" +
                    "\t\t\t\t<corpSN>123</corpSN>\n" +
                    "\t\t\t\t<state>90</state>\n" +
                    "\t\t\t\t<errorMessage>消息/errorMessage>\n" +
                    "\t\t\t</row>\n" +
                    "\t\t</tranflowResultList>\n" +
                    "\t</resBody>\n" +
                    "</ebank>\n";*/
            if (tmpStrRet[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                int index = tmpStrRet[1].indexOf("</ebank>");
                tmpStrRet[1] = tmpStrRet[1].substring(0,index+8);
                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    String returnCode = tmpBkReader.getFirstText("/ebank/resHead/retCode");
                    String returnMsg = tmpBkReader.getFirstText("/ebank/resHead/errMsg");
                    if (returnCode != null && isActiveRetCode(returnCode)) {
                        while(tmpBkReader.read("/ebank/resBody/tranflowResultList/row")){
                            //00：等待复核；01：复核被拒绝；10：等待授权；11：授权被拒绝；20：等待系统处理；
                            // 21：等待手工发送；48：等待加入处理队列（批量转账专用）49：等待发送主机（批量转账专用）；
                            // 50：主机处理中；90：交易成功；91：交易失败；92：交易作废；93：被银行取消；94：提交失败；
                            // 95：已中止 96:待发送已撤销  97:待复核已撤销   98:待授权已撤销 99：交易可疑
                            String state = tmpBkReader.readedXElement.getSingleText("state");
                            retDetail.respCode = "0";
                            retDetail.respInfo = tmpBkReader.readedXElement.getSingleText("errorMessage");;
                            retDetail.payInfoCode = returnCode +"+"+ state;
                            retDetail.transState = returnCode +"+"+ state;
                            retDetail.reqSeqID = p_req1944.askNumber;
                        }
                    } else {
                        retDetail.respCode = "-1";
                        retDetail.respInfo = returnMsg;
                    }
                } else {
                    retDetail.respCode = "-1";
                    retDetail.respInfo = tmpSbMsg.toString();
                }
            } else {
                retDetail.respCode = "-1";
                retDetail.respInfo = tmpStrRet[1];
            }
        } catch (Exception e) {
            retDetail.respCode = "-1";
            retDetail.respInfo = e.getMessage();
            e.printStackTrace();
        }

        retAts.writeRetDetail(retDetail);
        return retAts;
    }

    @Override
    public RetAtsSingleBat d_1944BAT_QrySglBatPay(ReqQrySingleBat p_req1944BAT) throws Exception {
        return null;
    }
}
